package me.flyray.bsin.util;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import io.dcloud.feature.sdk.DCUniMPSDK;
import io.dcloud.feature.sdk.Interface.IDCUniMPOnCapsuleCloseButtontCallBack;
import io.dcloud.feature.sdk.Interface.IMenuButtonClickCallBack;
import io.dcloud.feature.sdk.Interface.IOnUniMPEventCallBack;
import io.dcloud.feature.sdk.Interface.IUniMP;
import io.dcloud.feature.sdk.Interface.IUniMPOnCloseCallBack;
import io.dcloud.feature.unimp.DCUniMPJSCallback;
import io.dcloud.feature.unimp.config.IUniMPReleaseCallBack;
import io.dcloud.feature.unimp.config.UniMPReleaseConfiguration;

public class UniappUtil {
    /**
     * unimp小程序实例缓存
     **/
    public static HashMap<String, MyUniMP> mUniMPCaches = new HashMap<>();
    public static Context hostContext ;

    public static void initDCUniMPSDK(Context mcontext) {
        hostContext = mcontext;
        DCUniMPSDK.getInstance().setCapsuleCloseButtonClickCallBack(new IDCUniMPOnCapsuleCloseButtontCallBack() {
            @Override
            public void closeButtonClicked(String appid) {
                UniappUtil.closeUniMP(appid);
            }
        });

        DCUniMPSDK.getInstance().setUniMPOnCloseCallBack(new IUniMPOnCloseCallBack() {
            @Override
            public void onClose(String appid) {
                if (mUniMPCaches.containsKey(appid)) {
                    mUniMPCaches.remove(appid);
                }
                if(appid.equals("__UNI__C941DA7"))System.exit(0);
            }
        });

        DCUniMPSDK.getInstance().setDefMenuButtonClickCallBack(new IMenuButtonClickCallBack() {
            @Override
            public void onClick(String appid, String id) {
                MyUniMP uniMP = mUniMPCaches.get(appid);
                switch (id) {
                    case "gy": {
                        JSONObject data = new JSONObject();
                        break;
                    }
                    case "hqdqym": {
                        break;
                    }
                    case "gotoTestPage":
                        break;
                }
            }
        });
        DCUniMPSDK.getInstance().setOnUniMPEventCallBack(new IOnUniMPEventCallBack() {
            @Override
            public void onUniMPEventReceive(String appid, String event, Object data, DCUniMPJSCallback callback) {
                //更新返回函数
                if (mUniMPCaches.containsKey(appid)) {
                    mUniMPCaches.get(appid).mDCUniMPJSCallback = callback;
                }
                switch (event) {
                    case "DownloadAndOpen": {
                        try {
                            String version = ((JSONObject)data).getString("version");
                            String url = ((JSONObject)data).getString("url");
                            String uniappID = ((JSONObject)data).getString("uniappID");
                            openUniMP(version, url, uniappID, false, callback);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }
        });
    }

    public static void closeUniMP(String appid) {
        if (mUniMPCaches.containsKey(appid)) {
            MyUniMP mIUniMP = mUniMPCaches.get(appid);
            if (mIUniMP.mIunimp != null && mIUniMP.mIunimp.isRuning()) {
                mIUniMP.mIunimp.closeUniMP();
                mUniMPCaches.remove(appid);
            }
        }
    }

    public static void openUniMP(String version, String url, String uniappId, boolean host, DCUniMPJSCallback mDCUniMPJSCallback) {
        MyUniMP mMyUniMP = new MyUniMP();
        mMyUniMP.version = version;
        mMyUniMP.url = url;
        mMyUniMP.uniappId = uniappId;
        mMyUniMP.flag = 0;
        mMyUniMP.mDCUniMPJSCallback = mDCUniMPJSCallback;
        mUniMPCaches.put(uniappId, mMyUniMP);
        JSONObject backJson = new JSONObject();
        try {
            backJson.put("uniappID", uniappId);
            backJson.put("version", version);
            //本地是否已经存在当前小程序
            if (DCUniMPSDK.getInstance().isExistsApp(uniappId)) {
                JSONObject uniappInfo = DCUniMPSDK.getInstance().getAppVersionInfo(uniappId);
                if(uniappInfo==null){
                    backJson.put("flag", 1);
                    backJson.put("msg", "");
                    updateWgt(url, uniappId, "");
                    return;
                }
                String appVersion = uniappInfo.getString("name");
                //本地的小程序和目标小程序是否版本一致
                if (appVersion.equals(version)) {
                    IUniMP uniMP = DCUniMPSDK.getInstance().openUniMP(hostContext,uniappId);
                    backJson.put("flag", 0);
                    backJson.put("msg", "");
                    mMyUniMP.mIunimp = uniMP;
                }
                //版本不一致，下载更新
                else {
                    backJson.put("flag", 1);
                    backJson.put("msg", "");
                    updateWgt(url, uniappId, "");
                }
            }
            //没有本地小程序，下载更新
            else {
                backJson.put("flag", 1);
                backJson.put("msg", "");
                updateWgt(url, uniappId, "");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(mDCUniMPJSCallback!=null) mDCUniMPJSCallback.invokeAndKeepAlive(backJson);
    }

    public static class MyUniMP {
        public IUniMP mIunimp;
        public String version;
        public String url;
        public String uniappId;
        public int flag;
        public DCUniMPJSCallback mDCUniMPJSCallback;
    }

    /**
     * 模拟更新wgt
     */
    private static void updateWgt(String wgturl, String uniappId, String pd) {
        //
        final String wgtUrl = wgturl;
        final String wgtName = wgturl.substring(wgturl.lastIndexOf("/") + 1);
        String downFilePath = hostContext.getExternalCacheDir().getPath();
        Handler uiHandler = new Handler();
        DownloadUtil.get().download(hostContext, wgtUrl, downFilePath, wgtName, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                UniMPReleaseConfiguration uniMPReleaseConfiguration = new UniMPReleaseConfiguration();
                uniMPReleaseConfiguration.wgtPath = file.getPath();
                if (pd != null) uniMPReleaseConfiguration.password = "789456123";
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        DCUniMPSDK.getInstance().releaseWgtToRunPath(uniappId, uniMPReleaseConfiguration, new IUniMPReleaseCallBack() {
                            @Override
                            public void onCallBack(int code, Object pArgs) {
                                if (mUniMPCaches.containsKey(uniappId)) {
                                    MyUniMP mIUniMP = mUniMPCaches.get(uniappId);
                                    JSONObject backJson = new JSONObject();
                                    try {
                                        backJson.put("uniappID", uniappId);
                                        backJson.put("version", mIUniMP.version);
                                        if (code == 1) {
                                            //释放wgt完成
                                            Toast.makeText(hostContext, "加载应用成功", Toast.LENGTH_LONG).show();
                                            try {
                                                IUniMP uniMP = DCUniMPSDK.getInstance().openUniMP(hostContext, uniappId);
                                                backJson.put("msg", "成功");
                                                backJson.put("flag", 0);
                                                mIUniMP.mIunimp = uniMP;
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                Toast.makeText(hostContext, e.getMessage(), Toast.LENGTH_LONG);
                                                backJson.put("msg", e.getMessage());
                                                backJson.put("flag", 2);
                                                mUniMPCaches.remove(uniappId);
                                            }
                                        } else {
                                            Toast.makeText(hostContext, "加载应用失败", Toast.LENGTH_LONG).show();
                                            backJson.put("msg", "解压wgt包失败");
                                            backJson.put("flag", 2);
                                            mUniMPCaches.remove(uniappId);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    if( mIUniMP.mDCUniMPJSCallback!=null) mIUniMP.mDCUniMPJSCallback.invokeAndKeepAlive(backJson);
                                }
                            }
                        });
                    }
                });
            }

            @Override
            public void onDownloading(int progress) {
            }

            @Override
            public void onDownloadFailed() {
                if (mUniMPCaches.containsKey(uniappId)) {
                    MyUniMP mIUniMP = mUniMPCaches.get(uniappId);
                    JSONObject backJson = new JSONObject();
                    try {
                        backJson.put("uniappID", uniappId);
                        backJson.put("version", mIUniMP.version);
                        backJson.put("msg", "文件下载失败，请重试！");
                        backJson.put("flag", 2);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if(mIUniMP.mDCUniMPJSCallback!=null)mIUniMP.mDCUniMPJSCallback.invokeAndKeepAlive(backJson);
                    //失败了就删除缓存
                    mUniMPCaches.remove(uniappId);
                }
            }
        });
    }
}
